package zcw.com.lib_leet_code;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

import zcw.com.lib_leet_code.bean.Node;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/11/30.<br><br>
 *
 * 中等：填充每个节点的下一个右侧节点指针
 */
public class Topic116 {

    public static void main(String[] args) {
        Topic116 instance = new Topic116();
        Node root;

        root = Util.createTree2(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        instance.connect(root);
    }

    public Node connect(Node root) {
        if(root == null) {
            return null;
        }

        Node mostLeft = root;
        while (mostLeft.left != null) {
            Node head = mostLeft;

            while (head != null) {
                head.left.next = head.right;

                if(head.next != null) {
                    head.right.next = head.next.left;
                }

                head = head.next;
            }

            mostLeft = mostLeft.left;
        }

        return root;
    }

    public Node connect3(Node root) {
        helper2(root);
        return root;
    }

    private void helper2(Node root) {
        if(root == null) {
            return ;
        }


        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();

            Node prev = null;
            for(int i = 0; i < size; i++) {
                Node node = queue.poll();

                if(i > 0) {
                    prev.next = node;
                }

                prev = node;
                if(node.left != null) {
                    queue.offer(node.left);
                }


                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
    }

    public Node connect2(Node root) {
        helper(root);
        return root;
    }

    private void helper(Node root) {
        if(root == null) {
            return ;
        }

        Node endNode = new Node(Integer.MAX_VALUE);
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        queue.offer(endNode);

        Node prev = null;
        while (!queue.isEmpty()) {
            Node node = queue.poll();

            if(node.val == Integer.MAX_VALUE) {
                if(queue.isEmpty()) {
                    break;
                }

                queue.offer(endNode);
                prev = null;
                continue;
            }
            else {
                if(prev != null) {
                    prev.next = node;
                }
            }

            prev = node;
            if(node.left != null) {
                queue.offer(node.left);
            }

            if(node.right != null) {
                queue.offer(node.right);
            }
        }
    }
}
